package com.scienjus.serviceImpl;

import com.scienjus.config.Constants;
import com.scienjus.config.ResultStatus;
import com.scienjus.dao.SysPermissionDao;
import com.scienjus.dao.SysPermissionRoleDao;
import com.scienjus.dao.SysRoleDao;
import com.scienjus.dao.SysRoleUserDao;
import com.scienjus.domain.SysRole;
import com.scienjus.model.PermissionModel;
import com.scienjus.model.ResultModel;
import com.scienjus.repository.SysPermissionRepository;
import com.scienjus.service.SysRoleService;
import com.scienjus.tools.BaseTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.*;

/**
 * Created by MәӧωρaЯsε on 2017/6/21.
 * 角色
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    private static final Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysPermissionRepository sysPermissionRepository;
    @Autowired
    private SysPermissionRoleDao sysPermissionRoleDao;
    @Autowired
    private SysPermissionDao sysPermissionDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleUserDao sysRoleUserDao;

    @Override
    public ResultModel getRolePermission(int roleId) {

        String permissionIds = sysPermissionRoleDao.getRolePermission(roleId);

        if (!isPermissionExist(permissionIds)) {
            return ResultModel.error(ResultStatus.ROLE_NOTEXIST);
        }

        List<Integer> ids = BaseTools.strToList(permissionIds);

        List<PermissionModel> permissionModels = sysPermissionRepository.findMenu();

        for (PermissionModel permissionModel : permissionModels) {

            List<PermissionModel> list = getNodes(permissionModel.getId(), ids);

            if (list.isEmpty()) {
                if (ids.contains(permissionModel.getId()))
                    permissionModel.setChecked(true);
            } else {
                permissionModel.setPermissionModels(list);
                for (PermissionModel permission : list) {
                    permissionModel.setChecked(permission.getChecked());
                    if (!permission.getChecked()) {
                        break;
                    }
                }
            }
        }
        return ResultModel.ok(permissionModels);
    }

    @Override
    public ResultModel updateRolePermission(String pIds, int roleId) {

        //获得角色的权限
        String rPids = sysPermissionRoleDao.getRolePermission(roleId);
        if (!isPermissionExist(pIds)) {
            return ResultModel.error(ResultStatus.ROLE_NOTEXIST);
        }
        List<Integer> rPidList = BaseTools.strToList(rPids);

        //修改后的权限
        List<Integer> ids = BaseTools.strToList(pIds);
        Number num = (Number) request.getAttribute(Constants.CURRENT_USER_ID);
        int currentUserID = num.intValue();
        logger.info("pIds:{}", pIds);
        //获得当前用户所拥有的PIds
        String cPIds = sysPermissionDao.findAllByUserId(currentUserID);
        Set<Integer> cPidSet = BaseTools.strToSet(cPIds);
        List<Integer> cPidList = new ArrayList<>();
        cPidList.addAll(cPidSet);

        //获得不允许操作的PId,取cPidList和rPidList的差集
        rPidList.removeAll(cPidList);

        //去掉无权限的PId
        ids.removeIf(val -> !cPidList.contains(val));

        ids.addAll(rPidList);

        sysRoleDao.updateRolePermission(String.join(",", BaseTools.intListToStrList(ids)), roleId);

        return ResultModel.ok(getRolePermission(roleId));
    }

    @Override
    public ResultModel createRole(String roleName) {
        SysRole sysRole = new SysRole();
        sysRole.setName(roleName);
        SysRole role = sysRoleDao.findByName(roleName);
        if (role != null) {
            return ResultModel.error(ResultStatus.ROLENAME_EXIST);
        }
        sysRoleDao.save(sysRole);
        return ResultModel.ok();
    }

    @Override
    @Transactional
    public ResultModel deleteRole(int roleId) {

        Number num = (Number) request.getAttribute(Constants.CURRENT_USER_ID);
        int currentUserID = num.intValue();
        List<Integer> roleIds = sysRoleUserDao.findRoleIdByUserId(currentUserID);

        if (roleIds.contains(roleId)) {
            sysPermissionRoleDao.delete((long) roleId);
            sysRoleDao.delete(roleId);
            sysRoleUserDao.deleteByRoleId(roleId);
            return ResultModel.ok(true);
        }

        return ResultModel.error(ResultStatus.ROLE_DENIED);
    }

    //递归 取得下级菜单
    private List<PermissionModel> getNodes(int pid, List<Integer> ids) {

        List<PermissionModel> permissionModels = sysPermissionRepository.findMenu(pid);

        for (PermissionModel permissionModel : permissionModels) {

            List<PermissionModel> list = getNodes(permissionModel.getId(), ids);

            if (list.isEmpty()) {
                if (ids.contains(permissionModel.getId()))
                    permissionModel.setChecked(true);
            } else {
                permissionModel.setPermissionModels(list);
                for (PermissionModel permission : list) {
                    permissionModel.setChecked(permission.getChecked());
                    if (!permission.getChecked()) {
                        break;
                    }
                }
            }
        }
        return permissionModels;
    }

    private boolean isPermissionExist(String pIds) {
        return pIds != null;
    }

}
